package utils

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"time"
)

// DispatchRequest 发起请求
func DispatchRequest(method string, myUrl string, content interface{}) ([]byte, error) {
	timeout := time.Duration(10 * time.Second)
	client := http.Client{
		Timeout: timeout,
	}
	var contentBuffer *bytes.Buffer
	var req *http.Request
	var err error
	var jsonBytes []byte
	if method == "" || method == "GET" {
		req, err = http.NewRequest("GET", myUrl, nil)
	} else if method == "POST" {
		jsonBytes, err = json.Marshal(content)
		if err != nil {
			return []byte(""), err
		}
		contentBuffer = bytes.NewBuffer(jsonBytes)
		req, err = http.NewRequest(method, myUrl, contentBuffer)
	} else {
		return []byte(""), errors.New("请指定请求方式")
	}

	req.Header.Add("Content-Type", "application/json;charset=utf-8")
	if err != nil {
		return []byte(""), err
	}
	rsp, err := client.Do(req)
	if err != nil {
		return []byte(""), err
	}
	defer rsp.Body.Close()
	body, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return []byte(""), err
	}
	return body, nil
}

func HttpGet(myUrl string, content interface{}) ([]byte, error) {
	return DispatchRequest("GET", myUrl, content)
}
func HttpPost(myUrl string, content interface{}) ([]byte, error) {
	return DispatchRequest("POST", myUrl, content)
}
